package com.kirk.cts.core.event;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p> CrawlerToolObserver.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-31 19:27
 * @Description 事件观察者
 */
public class CrawlerToolObserver {

    private Logger logger = Logger.getLogger(this.getClass());

    private static CrawlerToolObserver observer;

    private CopyOnWriteArrayList<CrawlerToolListener> repository = new CopyOnWriteArrayList<CrawlerToolListener>();

    private CrawlerToolObserver() {
    }

    public static CrawlerToolObserver getInstance() {
        if (observer == null) {
            observer = new CrawlerToolObserver();
        }
        return observer;
    }

    public void addCrawlerListener(CrawlerToolListener crawlerListener) {
        repository.add(crawlerListener);
    }

    public void removeCrawlerListener(CrawlerToolListener crawlerListener) {
        repository.remove(crawlerListener);
    }

    @SuppressWarnings("unchecked")
    public void notifyEvents(CrawlerToolEvent crawlerEvent) {
        CopyOnWriteArrayList<CrawlerToolListener> tempList = null;
        synchronized (this) {
            tempList = (CopyOnWriteArrayList<CrawlerToolListener>) repository.clone();
            if (CollectionUtils.isNotEmpty(tempList)) {
                for (CrawlerToolListener listener : tempList) {
                    listener.update(crawlerEvent);
                }
            }
        }

    }
}
